package com.smedi.ismedi.progress.core.application.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.inmail.api.dto.request.MessageInfoRequest;
import com.smedi.ismedi.organization.api.dto.request.OrganizationListQueryRequest;
import com.smedi.ismedi.organization.api.dto.response.resp.OrganizationResp;
import com.smedi.ismedi.personnel.api.dto.request.OrganizationAssignmentListQueryRequest;
import com.smedi.ismedi.progress.core.application.command.*;
import com.smedi.ismedi.progress.core.application.query.VersionManageQueryService;
import com.smedi.ismedi.progress.core.application.service.ProgressApplicationService;
import com.smedi.ismedi.progress.core.application.service.ProgressReportApplicationService;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.Person;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.ProcessTask;
import com.smedi.ismedi.progress.core.domain.aggregatemodel.Progress;
import com.smedi.ismedi.progress.core.domain.dto.OrganizationQuery;
import com.smedi.ismedi.progress.core.domain.dto.PersonQuery;
import com.smedi.ismedi.progress.core.domain.repository.PersonRepository;
import com.smedi.ismedi.progress.core.domain.service.ProgrressReportDomainService;
import com.smedi.ismedi.progress.core.domain.service.VersionManageDomainService;
import com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField;
import com.smedi.ismedi.progress.core.port.adapter.service.MessageRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.OrganizationRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.ProcessRemoteService;
import com.smedi.ismedi.progress.core.port.adapter.service.TaskRemoteService;
import com.smedi.ismedi.web.starter.exception.ErrorItem;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.*;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.MethodEnum.NOT_PASS;
import static com.smedi.ismedi.progress.core.infrastructure.constant.ConstantField.MethodEnum.PASS;
import static com.smedi.ismedi.progress.core.infrastructure.constant.CustomError.DEAL_PERSON_NOT_FOUND;
import static com.smedi.ismedi.web.starter.thread.ThreadPool.IO_INSTANCE;

/**
 * 特种设备应用服务实现类
 *
 * @author xienannan
 * @date 2021/08/28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProgressApplicationServiceImpl implements ProgressApplicationService {

    @Value("${deal-people.review-organization.role}")
    private String dealPersonReviewOrganizationRole;

    @Value("${deal-people.review-institution.role}")
    private String dealPersonReviewInstitutionRole;

    @Value("${message-notify.project-manager.role}")
    private String messageNotifyProjectManagerRole;



    private final VersionManageQueryService versionManageQueryService;
    private final ProcessRemoteService processRemoteService;
    private final PersonRepository personRepository;
    private final TaskRemoteService taskRemoteService;
    private final AuthorityUtil authorityUtil;
    private final MessageRemoteService messageRemoteService;
    private final VersionManageDomainService versionManageDomainService;
    private final ProgrressReportDomainService progrressReportDomainService;
    private final ProgressReportApplicationService progressReportApplicationService;

    private final OrganizationRemoteService organizationRemoteService;

    @Override
    public void progressWorkorder(Progress progress) {
//        Progress progress =  versionManageDomainService.updateVersionManage(progress1);
        Progress  craneQueried = versionManageQueryService.getVersionManageOne(VersionManageOneQuery.builder().id(progress.getId()).build());
        //List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewOrganizationRole).organizationId(craneQueried.getProject().getHrOrganizationId()).build());
        List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(craneQueried.getProjectId()).build());
        if (dealPeopleReviewOrganization.isEmpty()){
//            throw LogicException.raise(new ErrorItem(30, "未找到对应项目的主体院下的主体院总承包部经理角色，请配置主体院总承包部经理角色"));
            OrganizationResp organization = organizationRemoteService.getOrganizationOne(OrganizationQuery.builder().id(craneQueried.getProject().getHrOrganizationId()).build());
            throw LogicException.raise(DEAL_PERSON_NOT_FOUND, organization.getShortName(), this.messageNotifyProjectManagerRole, ROLE);

        }
        processRemoteService.startProcessInstance(ProcessInstanceStartCommand.builder()
                .businessCode(String.valueOf(progress.getId()))
                .businessType(ConstantField.CRANE)
                //.processDefinitionKey(ConstantField.PROCESS_CRANE)
                .processDefinitionKey(ConstantField.PROCESS_VERSION)
                .build());
        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(progress.getId()))
                .businessType(CRANE)
                //.processDefinitionKey(PROCESS_CRANE)
                .processDefinitionKey(ConstantField.PROCESS_VERSION)
                .build());
        craneQueried.setTaskStatus(processTask.getStatus());
        craneQueried.setTaskKey(processTask.getTaskDefinitionKey());
        craneQueried.setMainCourtyardApproval(1l);
        craneQueried.setStatus(0l);
//        craneQueried.setSubmitTime(LocalDateTime.now());
        versionManageDomainService.updateVersionManage(craneQueried);
        // 更新版本表

        for (Person person : dealPeopleReviewOrganization) {
            // 发送待办
            taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                    .sourceFromId(craneQueried.getId())
                    .taskType(TASK_TYPE)
                    .taskName(TASK_NAME_PROGRESS_CONSTRUCTION_APPROVAL)
                    .taskDescribe(PROGRESS_MESSAGE)
                    .dealPersonId(person.getId())
                    .dealPersonName(person.getName())
                    .taskStatus("进行中")
                    .projectId(craneQueried.getProject().getId())
                    .projectName(craneQueried.getProject().getName())
                    .sponsorId(authorityUtil.getPersonId())
                    .sponsorName(authorityUtil.getLoginAccess().getLastName())
                    .startTime(LocalDateTime.now())
                    .build());
            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(ConstantField.WEEK_MONTH_PREGRESS)
                    .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(person.getName(), ConstantField.TASK_TYPE,progress.getName())))
                    .build());
        }
    }

    @Override
    @Transactional
    /**
     * 主体院审批
     */
    public Progress reviewPojectProgress(ProgressReviewProjectCommand progressReviewProjectCommand) {
        /*Progress  versionManage = versionManageQueryService.getVersionManageOne(VersionManageOneQuery.builder().id(progressReviewProjectCommand.getId()).build());

        Progress versionManageQueried = versionManageQueryService.getVersionManageOne(VersionManageOneQuery.builder().id(versionManage.getId()).build());
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(versionManageQueried.getProjectId());
        String projectName = null;
        String projectId = null;
        String hrOrganizationFullName = null;
        if (projectData != null){
            if (projectData.getProjectName() != null ){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null ){
                projectId = String.valueOf(projectData.getProjectId());
            }
            if (projectData.getHrOrganizationFullName() != null ){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
        }
        List<Person> dealPeopleReviewInstitution = personRepository.getPersonList(PersonQuery.builder().roleName(dealPersonReviewInstitutionRole).build());
        if (dealPeopleReviewInstitution.isEmpty()){
//            throw LogicException.raise(new ErrorItem(29, "未找到对应的项目的工程管理部控制经理，请配置工程管理部控制经理角色"));
            throw LogicException.raise(DEAL_PERSON_NOT_FOUND, hrOrganizationFullName, this.dealPersonReviewInstitutionRole, ROLE);

        }
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, progressReviewProjectCommand.getMethod());

        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(versionManageQueried.getId()))
                .businessType(CRANE)
                .processDefinitionKey(PROCESS_CRANE)
                .comment(progressReviewProjectCommand.getComment())
                .variables(variables)
                .build());
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(versionManageQueried.getId())
                .taskType(TASK_TYPE)
                .taskName(TASK_NAME_PROGRESS_APPROVAL)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());
        if (progressReviewProjectCommand.getMethod().equals(PASS.name())) {
            versionManageQueried.setTaskStatus(processTask.getStatus());
            versionManageQueried.setTaskKey(processTask.getTaskDefinitionKey());
            versionManageQueried.setMainCourtyardApproval(2l);
            versionManageQueried.setEngineerDepartmentApproval(1l);
            versionManageQueried.setLatestUpdatedUserId(authorityUtil.getPersonId());
            versionManageQueried.setLatestUpdatedDate(LocalDateTime.now());
            versionManageDomainService.updateVersionManage(versionManageQueried);

            for (Person person : dealPeopleReviewInstitution) {
                taskRemoteService.createTask(TaskRecordCreateCommand.builder()
                        .sourceFromId(versionManageQueried.getId())
                        .dealPersonId(person.getId())
                        .dealPersonName(person.getName())
                        .taskType(TASK_TYPE)
                        .taskName(TASK_NAME_PROGRESS_INSTITUTION_APPROVAL)
                        .taskDescribe(PROGRESS_MESSAGE)
                        .taskStatus("进行中")
                        .projectId(versionManageQueried.getProject().getId())
                        .projectName(versionManageQueried.getProject().getName())
                        .sponsorId(authorityUtil.getPersonId())
                        .sponsorName(authorityUtil.getLoginAccess().getLastName())
                        .startTime(LocalDateTime.now())
                        .build());
                // 发送短信
                messageRemoteService.sendMessage(MessageSendCommand.builder()
                        .smsTemplateName(ConstantField.WEEK_MONTH_PREGRESS)
                        .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                        .parameters(new ArrayList<>(Arrays.asList(person.getName(), ConstantField.TASK_TYPE,projectName)))
                        .build());
            }
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_TEMPLATE_PROGRESS_PASS)
                    .mobiles(new ArrayList<>(Collections.singletonList(versionManageQueried.getApplicant().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(versionManageQueried.getApplicant().getName(), versionManageQueried.getProject().getName(),TASK_TYPE)))
                    .build());
        }

        if (progressReviewProjectCommand.getMethod().equals(NOT_PASS.name())) {
            versionManageQueried.setMainCourtyardApproval(0l);
            versionManageQueried.setLatestUpdatedUserId(authorityUtil.getPersonId());
            versionManageQueried.setLatestUpdatedDate(LocalDateTime.now());
            versionManageQueried.setReason(progressReviewProjectCommand.getComment());
            versionManageQueried.setTaskStatus(ConstantField.FINISHED);
            versionManageQueried.setTaskKey(ConstantField.ACTIVITY_FINISH);
            versionManageDomainService.updateVersionManage(versionManageQueried);
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_TEMPLATE_PROGRESS_BACK)
                    .mobiles(new ArrayList<>(Collections.singletonList(versionManageQueried.getApplicant().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(versionManageQueried.getApplicant().getName(), versionManageQueried.getProject().getName(),TASK_TYPE)))
                    .build());
            // 发送消息
            MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
            MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
            List<MessageInfoRequest> listDate = new ArrayList<>();
            messageInfoRequests.setMessageTitle(ConstantField.APPROVAL_RESULTS);
            messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
            messageInfoRequests.setProjectId(projectId);
            messageInfoRequests.setProjectName(projectName);
            messageInfoRequests.setPushTime(LocalDateTime.now());
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START + hrOrganizationFullName+"的" +projectName+ ConstantField.TASK_TYPE+ConstantField.MESSAGE_CONTENT_NO_PASS_END_NEW);
            listDate.add(messageInfoRequests);
            messagesSendPostCommand.setMessageInfoRequests(listDate);
            messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(versionManageQueried.getApplicant().getId())));
            taskRemoteService.postSendMessage(messagesSendPostCommand);
        }

        return versionManageQueried;*/
        /**
         * 改成由 施工项目经理 审批，审批完成后流程结束 --2024-07-10
         */
        Progress  versionManage = versionManageQueryService.getVersionManageOne(VersionManageOneQuery.builder().id(progressReviewProjectCommand.getId()).build());
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, progressReviewProjectCommand.getMethod());
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(versionManage.getProjectId());
        String projectName = null;
        String projectId = null;
        String hrOrganizationFullName = null;
        if (projectData != null){
            if (projectData.getProjectName() != null ){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null ){
                projectId = String.valueOf(projectData.getProjectId());
            }
            if (projectData.getHrOrganizationFullName() != null ){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
        }
        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(versionManage.getId()))
                .businessType(CRANE)
                .processDefinitionKey(PROCESS_VERSION)
                .comment(progressReviewProjectCommand.getComment())
                .variables(variables)
                .build());
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(versionManage.getId())
                .taskType(TASK_TYPE)
                .taskName(TASK_NAME_PROGRESS_CONSTRUCTION_APPROVAL)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());
        MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
        MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
        List<MessageInfoRequest> listDate = new ArrayList<>();
        messageInfoRequests.setMessageTitle(ConstantField.APPROVAL_RESULTS);
        messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
        messageInfoRequests.setProjectId(projectId);
        messageInfoRequests.setProjectName(projectName);
        messageInfoRequests.setPushTime(LocalDateTime.now());
        List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(versionManage.getProjectId()).build());

        String constructManager = null;
        if (!messageNotifyProjectManager.isEmpty()){
            constructManager = StringUtils.strip(messageNotifyProjectManager.stream().distinct().map(Person ->Person.getName()).collect(Collectors.toList()).toString(),"[]");
        }
        versionManage.setConstructManager(constructManager);
        if (progressReviewProjectCommand.getMethod().equals(PASS.name())) {
            versionManage.setTaskStatus(ConstantField.FINISHED);
            versionManage.setTaskKey(ConstantField.ACTIVITY_FINISH);
            versionManage.setStatus(1l);
            versionManage.setMainCourtyardApproval(2l);
            versionManage.setLatestUpdatedUserId(authorityUtil.getPersonId());
            versionManage.setLatestUpdatedDate(LocalDateTime.now());
            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_VERSION_PROGRESS_APPROVAL)
                    .mobiles(new ArrayList<>(Collections.singletonList(versionManage.getApplicant().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(versionManage.getApplicant().getName(), versionManage.getProject().getName(),TASK_TYPE)))
                    .build());
            // 发送消息
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START +hrOrganizationFullName+"的"+projectName+ ConstantField.TASK_TYPE+ConstantField.MESSAGE_CONTENT_PASS_END);
            // 需要将项目插入到对应的项目表中 先查询下项目表中是否存在对应的项目
            versionManageDomainService.selectAndUpdate(versionManage,projectData);
            long time1 = System.currentTimeMillis();
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    CompletableFuture.allOf(
                            CompletableFuture.runAsync(() -> progrressReportDomainService.updateProgressReportData(versionManage), IO_INSTANCE),
                            CompletableFuture.runAsync(() -> progressReportApplicationService.AutoApproveReturn(versionManage), IO_INSTANCE)
                    ).join();
                }
            });
            thread.start();
            long time2 = System.currentTimeMillis();
            log.info("进度计划审批处理时间====={}", time2-time1);
            /**
             * 修改低版本号，待审批状态的消息为已处理
             */
            List<Long> verisonDownIds = versionManageDomainService.getVersionDownByVersionNoAndProjectId(versionManage.getVersion(),versionManage.getProjectId());
            verisonDownIds.forEach(versionDownId ->{
                taskRemoteService.editTask(TaskRecordEditCommand.builder()
                        .sourceFromId(versionDownId)
                        .taskType(TASK_TYPE)
                        .taskName(TASK_NAME_PROGRESS_CONSTRUCTION_APPROVAL)
                        .taskStatus("已完成")
                        .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                        .finishTime(LocalDateTime.now())
                        .build());
            });
            versionManageDomainService.editVersionNullify(versionManage.getVersion(),versionManage.getProjectId());



        }
        if (progressReviewProjectCommand.getMethod().equals(NOT_PASS.name())) {
            versionManage.setMainCourtyardApproval(0l);
            versionManage.setReason(progressReviewProjectCommand.getComment());
            versionManage.setLatestUpdatedUserId(authorityUtil.getPersonId());
            versionManage.setLatestUpdatedDate(LocalDateTime.now());
            versionManage.setTaskStatus(ConstantField.FINISHED);
            versionManage.setTaskKey(ConstantField.ACTIVITY_FINISH);
            versionManage.setStatus(0l);
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_VERSION_RETURN)
                    .mobiles(new ArrayList<>(Collections.singletonList(versionManage.getApplicant().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(versionManage.getApplicant().getName(), versionManage.getProject().getName(),TASK_TYPE)))
                    .build());
            // 发送消息
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START  +hrOrganizationFullName+"的"+projectName +ConstantField.TASK_TYPE+ConstantField.MESSAGE_CONTENT_NO_PASS_END_NEW);
        }
        listDate.add(messageInfoRequests);
        messagesSendPostCommand.setMessageInfoRequests(listDate);
        messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(versionManage.getApplicant().getId())));
        taskRemoteService.postSendMessage(messagesSendPostCommand);
        return versionManageDomainService.updateVersionManage(versionManage);
    }

    @Override
    @Transactional
    /**
     * 工程部审批
     */
    public Progress reviewPojectProgressInstitution(ProgressReviewProjectCommand progressReviewProjectCommand) {
        Progress  versionManage = versionManageQueryService.getVersionManageOne(VersionManageOneQuery.builder().id(progressReviewProjectCommand.getId()).build());
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, progressReviewProjectCommand.getMethod());
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(versionManage.getProjectId());
        String projectName = null;
        String projectId = null;
        String hrOrganizationFullName = null;
        if (projectData != null){
            if (projectData.getProjectName() != null ){
                projectName = projectData.getProjectName();
            }
            if (projectData.getProjectId() != null ){
                projectId = String.valueOf(projectData.getProjectId());
            }
            if (projectData.getHrOrganizationFullName() != null ){
                hrOrganizationFullName = projectData.getHrOrganizationFullName();
            }
        }
        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(versionManage.getId()))
                .businessType(CRANE)
                .processDefinitionKey(PROCESS_CRANE)
                .comment(progressReviewProjectCommand.getComment())
                .variables(variables)
                .build());
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(versionManage.getId())
                .taskType(TASK_TYPE)
                .taskName(TASK_NAME_PROGRESS_INSTITUTION_APPROVAL)
                .taskStatus("已完成")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());
        MessagesSendPostCommand messagesSendPostCommand = new MessagesSendPostCommand();
        MessageInfoRequest messageInfoRequests = new MessageInfoRequest();
        List<MessageInfoRequest> listDate = new ArrayList<>();
        messageInfoRequests.setMessageTitle(ConstantField.APPROVAL_RESULTS);
        messageInfoRequests.setMessageType(ConstantField.MESSAGE_TYPE);
        messageInfoRequests.setProjectId(projectId);
        messageInfoRequests.setProjectName(projectName);
        messageInfoRequests.setPushTime(LocalDateTime.now());
        List<Person> messageNotifyProjectManager = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(versionManage.getProjectId()).build());

        String constructManager = null;
        if (!messageNotifyProjectManager.isEmpty()){
            constructManager = StringUtils.strip(messageNotifyProjectManager.stream().distinct().map(Person ->Person.getName()).collect(Collectors.toList()).toString(),"[]");
        }
        versionManage.setConstructManager(constructManager);
        if (progressReviewProjectCommand.getMethod().equals(PASS.name())) {
            versionManage.setTaskStatus(ConstantField.FINISHED);
            versionManage.setTaskKey(ConstantField.ACTIVITY_FINISH);
            versionManage.setStatus(1l);
            versionManage.setEngineerDepartmentApproval(2l);
            versionManage.setLatestUpdatedUserId(authorityUtil.getPersonId());
            versionManage.setLatestUpdatedDate(LocalDateTime.now());
            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_TEMPLATE_PROGRESS_APPROVAL)
                    .mobiles(new ArrayList<>(Collections.singletonList(versionManage.getApplicant().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(versionManage.getApplicant().getName(), versionManage.getProject().getName(),TASK_TYPE)))
                    .build());
            // 发送消息
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START +hrOrganizationFullName+"的"+projectName+ ConstantField.TASK_TYPE+ConstantField.MESSAGE_CONTENT_PASS_END);
            // 需要将项目插入到对应的项目表中 先查询下项目表中是否存在对应的项目
            versionManageDomainService.selectAndUpdate(versionManage,projectData);
            long time1 = System.currentTimeMillis();
            CompletableFuture.allOf(
                CompletableFuture.runAsync(() -> progrressReportDomainService.updateProgressReportData(versionManage), IO_INSTANCE),
                CompletableFuture.runAsync(() -> progressReportApplicationService.AutoApproveReturn(versionManage), IO_INSTANCE)
            ).join();

            long time2 = System.currentTimeMillis();
            log.info("进度计划审批处理时间====={}", time2-time1);
            // 更新周月报 状态为审批中，审批状态为已待审批 自动退回流程
//            progressReportApplicationService.AutoApproveReturn(versionManage);
            // 更新周月报数据
//            progrressReportDomainService.updateProgressReportData(versionManage);
        }
        if (progressReviewProjectCommand.getMethod().equals(NOT_PASS.name())) {
            versionManage.setEngineerDepartmentApproval(0l);
            versionManage.setReason(progressReviewProjectCommand.getComment());
            versionManage.setLatestUpdatedUserId(authorityUtil.getPersonId());
            versionManage.setLatestUpdatedDate(LocalDateTime.now());
            versionManage.setTaskStatus(ConstantField.FINISHED);
            versionManage.setTaskKey(ConstantField.ACTIVITY_FINISH);


            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(SMS_TEMPLATE_INSTITUTION_PROGRESS_BACK)
                    .mobiles(new ArrayList<>(Collections.singletonList(versionManage.getApplicant().getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(versionManage.getApplicant().getName(), versionManage.getProject().getName(),TASK_TYPE)))
                    .build());
            // 发送消息
            messageInfoRequests.setMessageContent(ConstantField.MESSAGE_CONTENT_START  +hrOrganizationFullName+"的"+projectName +ConstantField.TASK_TYPE+ConstantField.MESSAGE_CONTENT_NO_PASS_END_NEW);
        }
        listDate.add(messageInfoRequests);
        messagesSendPostCommand.setMessageInfoRequests(listDate);
        messagesSendPostCommand.setUserIds(new ArrayList<>(Collections.singletonList(versionManage.getApplicant().getId())));
        taskRemoteService.postSendMessage(messagesSendPostCommand);
        return versionManageDomainService.updateVersionManage(versionManage);
    }

    @Override
    public void cancelPojectProgress(Progress progress) {
        /*taskRemoteService.cancelTask(TaskRecordEditCommand.builder()
                        .sourceFromId(progressEntity.getId())
                        .projectId(progressEntity.getProjectId())
                        .taskStatus("已撤销")
                        .build());*/
        ProjectBasicResponse projectData = progrressReportDomainService.getProject(progress.getProjectId());
        taskRemoteService.editTask(TaskRecordEditCommand.builder()
                .sourceFromId(progress.getId())
                .taskType(TASK_TYPE)
                .taskName(TASK_NAME_PROGRESS_CONSTRUCTION_APPROVAL)
                .taskStatus("已撤销")
                .oldStatus(new ArrayList<>(Collections.singletonList("进行中")))
                .finishTime(LocalDateTime.now())
                .build());
        //发送短信给施工项目经理
        List<Person> dealPeopleReviewOrganization = personRepository.getPersonList(PersonQuery.builder().projectJob(messageNotifyProjectManagerRole).projectId(progress.getProjectId()).build());
        for (Person person : dealPeopleReviewOrganization) {
            // 发送短信
            messageRemoteService.sendMessage(MessageSendCommand.builder()
                    .smsTemplateName(ConstantField.SMS_VERSION_CANCEL)
                    .mobiles(new ArrayList<>(Collections.singletonList(person.getMobile())))
                    .parameters(new ArrayList<>(Arrays.asList(person.getName(), projectData.getProjectName())))
                    .build());
        }
        //流程停止
        Map<String, Object> variables = new HashMap<>();
        variables.put(METHOD, NOT_PASS.name());
        ProcessTask processTask = processRemoteService.completeProcessTask(ProcessTaskCompleteCommand.builder()
                .businessCode(String.valueOf(progress.getId()))
                .businessType(CRANE)
                .processDefinitionKey(PROCESS_VERSION)
                .comment("已撤销")
                .variables(variables)
                .build());
    }
}
